/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fbv.tcc.gui;

import fbv.tcc.chart.GraficoRadiacao;
import fbv.tcc.classes.PontoRadiacao;
import fbv.tcc.modelo.ModeloFisico;
import fbv.tcc.utils.PropertiesGenerator;
import fbv.tcc.utils.Utils;
import fbv.tcc.xls.WriteExcel;
import fbv.tcc.xls.XlsReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;

/**
 *
 * @author Casa
 */
public class Programa extends javax.swing.JFrame {

    public ArrayList<PontoRadiacao> pontosPlanilhaList = new ArrayList<PontoRadiacao>();
    public ArrayList<PontoRadiacao> pontosModeloFisicoList = new ArrayList<PontoRadiacao>();
    public ArrayList<String> nomesPlanilhas = new ArrayList<String>();

    class XLSFilter extends FileFilter {

        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            }

            String extension = Utils.getExtension(file);
            if (extension != null) {
                if (extension.equals(Utils.xls) || extension.equals(Utils.xlsx)) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            // Esta descrição será exibida na caixa de diálogo,
            // hard-coded = ugly, deve ser feito via I18N
            return "Planihas (*.xls, *.xlsx)";
        }
    }

    /**
     * Creates new form main
     */
    public Programa() {

        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        btnGraficoBarra = new javax.swing.JButton();
        btnCarregarPlanilhas = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        btnGerarPlanilhaOcorrencia = new javax.swing.JButton();
        btnGerarGrafico = new javax.swing.JButton();
        btnConfigurador = new javax.swing.JButton();
        btnSobre = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("PIG 2");
        setName("main"); // NOI18N
        setResizable(false);
        java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
        layout.columnWidths = new int[] {0, 10, 0, 10, 0, 10, 0, 10, 0, 10, 0};
        layout.rowHeights = new int[] {0, 10, 0, 10, 0, 10, 0};
        getContentPane().setLayout(layout);

        btnGraficoBarra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/barChartIcon.png"))); // NOI18N
        btnGraficoBarra.setText("Gráfico Barra");
        btnGraficoBarra.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGraficoBarra.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGraficoBarra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGraficoBarraActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnGraficoBarra, gridBagConstraints);

        btnCarregarPlanilhas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/excelIcon.png"))); // NOI18N
        btnCarregarPlanilhas.setText("Carregar Planilhas");
        btnCarregarPlanilhas.setToolTipText("Carregar Planilhas");
        btnCarregarPlanilhas.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnCarregarPlanilhas.setIconTextGap(1);
        btnCarregarPlanilhas.setMargin(new java.awt.Insets(2, 5, 2, 5));
        btnCarregarPlanilhas.setMaximumSize(new java.awt.Dimension(95, 75));
        btnCarregarPlanilhas.setMinimumSize(new java.awt.Dimension(95, 75));
        btnCarregarPlanilhas.setName(""); // NOI18N
        btnCarregarPlanilhas.setPreferredSize(new java.awt.Dimension(120, 73));
        btnCarregarPlanilhas.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnCarregarPlanilhas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCarregarPlanilhasActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnCarregarPlanilhas, gridBagConstraints);

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/closeIcon.png"))); // NOI18N
        btnSair.setText("Sair");
        btnSair.setToolTipText("Fechar programa");
        btnSair.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSair.setIconTextGap(1);
        btnSair.setMaximumSize(new java.awt.Dimension(95, 75));
        btnSair.setMinimumSize(new java.awt.Dimension(95, 75));
        btnSair.setPreferredSize(new java.awt.Dimension(120, 75));
        btnSair.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 8;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnSair, gridBagConstraints);

        btnGerarPlanilhaOcorrencia.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/report_icon.png"))); // NOI18N
        btnGerarPlanilhaOcorrencia.setText("Gerar P. de Ocorrências");
        btnGerarPlanilhaOcorrencia.setToolTipText("Carregar Planilhas");
        btnGerarPlanilhaOcorrencia.setDefaultCapable(false);
        btnGerarPlanilhaOcorrencia.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGerarPlanilhaOcorrencia.setIconTextGap(1);
        btnGerarPlanilhaOcorrencia.setMargin(new java.awt.Insets(2, 5, 2, 5));
        btnGerarPlanilhaOcorrencia.setMaximumSize(new java.awt.Dimension(95, 75));
        btnGerarPlanilhaOcorrencia.setMinimumSize(new java.awt.Dimension(95, 75));
        btnGerarPlanilhaOcorrencia.setName(""); // NOI18N
        btnGerarPlanilhaOcorrencia.setPreferredSize(new java.awt.Dimension(120, 73));
        btnGerarPlanilhaOcorrencia.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGerarPlanilhaOcorrencia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarPlanilhaOcorrenciaActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnGerarPlanilhaOcorrencia, gridBagConstraints);

        btnGerarGrafico.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/graphIcon.png"))); // NOI18N
        btnGerarGrafico.setText("Gerar Gráficos");
        btnGerarGrafico.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGerarGrafico.setMaximumSize(new java.awt.Dimension(95, 75));
        btnGerarGrafico.setMinimumSize(new java.awt.Dimension(95, 75));
        btnGerarGrafico.setPreferredSize(new java.awt.Dimension(120, 73));
        btnGerarGrafico.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGerarGrafico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGerarGraficoActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnGerarGrafico, gridBagConstraints);

        btnConfigurador.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/config.png"))); // NOI18N
        btnConfigurador.setText("Configurar");
        btnConfigurador.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnConfigurador.setMaximumSize(new java.awt.Dimension(95, 75));
        btnConfigurador.setMinimumSize(new java.awt.Dimension(95, 75));
        btnConfigurador.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnConfigurador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfiguradorActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 0.1;
        getContentPane().add(btnConfigurador, gridBagConstraints);

        btnSobre.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fbv/tcc/imgs/pigIcon.png"))); // NOI18N
        btnSobre.setText("Sobre");
        btnSobre.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSobre.setIconTextGap(1);
        btnSobre.setMaximumSize(new java.awt.Dimension(95, 75));
        btnSobre.setMinimumSize(new java.awt.Dimension(95, 75));
        btnSobre.setPreferredSize(new java.awt.Dimension(120, 75));
        btnSobre.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSobreActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(btnSobre, gridBagConstraints);

        getAccessibleContext().setAccessibleName("PIG 2");
        getAccessibleContext().setAccessibleDescription("PIG 2");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCarregarPlanilhasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCarregarPlanilhasActionPerformed


        pontosPlanilhaList.clear();
        pontosModeloFisicoList.clear();
        nomesPlanilhas.clear();

        Properties res = null;
        try {
            res = PropertiesGenerator.carregarProperties();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        }

        File caminhoPlanilha = new File(res.getProperty("caminho"));

        //GUI
        JFileChooser jFileChooserPlanilhas = new JFileChooser();
        jFileChooserPlanilhas.setAcceptAllFileFilterUsed(false);
        jFileChooserPlanilhas.setMultiSelectionEnabled(true);
        jFileChooserPlanilhas.setCurrentDirectory(caminhoPlanilha);
        jFileChooserPlanilhas.addChoosableFileFilter(new XLSFilter());
        int returnVal = jFileChooserPlanilhas.showOpenDialog(this);

        //NEGOCIO


        //PontoRadiacaoCompare pontoCompare = new PontoRadiacaoCompare();
        XlsReader xls = new XlsReader();


        if ((returnVal == JFileChooser.APPROVE_OPTION)) {
            File[] sheets = jFileChooserPlanilhas.getSelectedFiles();

            for (int i = 0; i < sheets.length; i++) {
                try {
                    pontosPlanilhaList.addAll(xls.loadSheetFile(sheets[i].getPath()));
                    nomesPlanilhas.add(sheets[i].getName());

                } catch (FileNotFoundException ex) {
                    JOptionPane optionPane = new JOptionPane();
                    optionPane.setMessage("Erro: Planilha não encontrada!");
                    optionPane.setMessageType(JOptionPane.ERROR_MESSAGE);
                    JDialog dialog = optionPane.createDialog(null, "Aviso");
                    dialog.setVisible(true);
                } catch (ParseException ex) {
                    Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
                } catch (BiffException ex) {
                    Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane optionPane = new JOptionPane();
            optionPane.setMessage("Planilha Carregada!");
            optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
            JDialog dialog = optionPane.createDialog(null, "Aviso");
            dialog.setVisible(true);
        } else {
            JOptionPane optionPane = new JOptionPane();
            optionPane.setMessage("Erro: Ação cancelada pelo usuário.");
            optionPane.setMessageType(JOptionPane.CANCEL_OPTION);
            JDialog dialog = optionPane.createDialog(null, "Aviso");
            dialog.setVisible(true);
        }
    }//GEN-LAST:event_btnCarregarPlanilhasActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnSairActionPerformed

    private void btnSobreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSobreActionPerformed
        Sobre janela = new Sobre();
        janela.setVisible(true);
    }//GEN-LAST:event_btnSobreActionPerformed

    private void btnGerarGraficoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarGraficoActionPerformed

        
        //ao clicar em gerar gráfico, deverá ser montado um arraylist com os mesmo horarios, porém com radiacoes originadas
        //do modelo fisico. Com os dois arrays passados como parametro, o gráfico será criado.
        ModeloFisico modelo = new ModeloFisico();

        //para cada pontoradiacao da planilha...
        for (PontoRadiacao ptr : pontosPlanilhaList) {


            try {
                //adicione no arraylist um novo pontoradiacao contendo o mesmo timestamp, porem agora com a nova radiação
                pontosModeloFisicoList.add(new PontoRadiacao(ptr.getTimeStamp(), modelo.calculaRadiacaoET(ptr)));

            } catch (FileNotFoundException ex) {
                JOptionPane optionPane = new JOptionPane();
                optionPane.setMessage("Erro: Planilha não encontrada!");
                optionPane.setMessageType(JOptionPane.ERROR_MESSAGE);
                JDialog dialog = optionPane.createDialog(null, "Aviso");
                dialog.setVisible(true);
            } catch (IOException ex) {
                JOptionPane optionPane = new JOptionPane();
                optionPane.setMessage("Erro: Problema de leitura da planilha!");
                optionPane.setMessageType(JOptionPane.ERROR_MESSAGE);
                JDialog dialog = optionPane.createDialog(null, "Aviso");
                dialog.setVisible(true);
            }
        }

        GraficoRadiacao g = new GraficoRadiacao();
        try {
            g.separarPontoRadiacao(pontosPlanilhaList, pontosModeloFisicoList);
        } catch (IOException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
        JOptionPane optionPane = new JOptionPane();
        optionPane.setMessage("Geração dos gráficos concluída!");
        optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
        JDialog dialog = optionPane.createDialog(null, "Aviso");
        dialog.setVisible(true);

    }//GEN-LAST:event_btnGerarGraficoActionPerformed

    private void btnConfiguradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfiguradorActionPerformed
        Configurador config = new Configurador();
        config.setVisible(true);
    }//GEN-LAST:event_btnConfiguradorActionPerformed

    private void btnGraficoBarraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGraficoBarraActionPerformed

        GraficoRadiacao g = new GraficoRadiacao();

        try {
            g.renderizarGraficoBarra();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnGraficoBarraActionPerformed

    private void btnGerarPlanilhaOcorrenciaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGerarPlanilhaOcorrenciaActionPerformed

        GraficoRadiacao g = new GraficoRadiacao();
        try {
            g.exportarDadosXLS(pontosPlanilhaList, pontosModeloFisicoList);
            //        Properties res = null;
    //        try {
    //            res = PropertiesGenerator.carregarProperties();
    //        } catch (FileNotFoundException ex) {
    //            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
    //        } catch (IOException ex) {
    //            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
    //        }
    //        String caminhoArquivoXLS = res.getProperty("caminhoArquivoXLS");
    //
    //        for (String arquivo : nomesPlanilhas) {
    //
    //            WriteExcel saida = new WriteExcel();
    //            saida.setOutputFile(caminhoArquivoXLS + arquivo);
    //            saida.write(g.planilha, g.modelo);
    //        }
    //        }
        } catch (IOException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WriteException ex) {
            Logger.getLogger(Programa.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnGerarPlanilhaOcorrenciaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows XP".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Programa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Programa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Programa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Programa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Programa().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCarregarPlanilhas;
    private javax.swing.JButton btnConfigurador;
    private javax.swing.JButton btnGerarGrafico;
    private javax.swing.JButton btnGerarPlanilhaOcorrencia;
    private javax.swing.JButton btnGraficoBarra;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSobre;
    // End of variables declaration//GEN-END:variables
}
